package AssetHelper


import (
	"embed"
	"io/fs"
	"net/http"
	"os"
	"path"
)

/**
静态文件打包处理
*/
type fsFunc func(name string) (fs.File, error)

func (f fsFunc) Open(name string) (fs.File, error) {
	return f(name)
}

// AssetHandler returns an http.Handler that will serve files from
// the Assets embed.FS. When locating a file, it will strip the given
// prefix from the request and prepend the root to the filesystem.
func AssetHandler(prefix string, assets *embed.FS, root string) http.Handler {
	handler := fsFunc(func(name string) (fs.File, error) {
		assetPath := path.Join(root, name)
		// If we can't find the asset, fs can handle the error
		file, err := assets.Open(assetPath)

		if err != nil {
			return nil, err
		}
		//以下禁止访问目录
		as,aerr := file.Stat()
		if aerr!=nil{
			return nil, os.ErrNotExist
		}
		if as.IsDir(){
			return nil,os.ErrNotExist
		}
		// Otherwise assume this is a legitimate request routed correctly
		return file, err
	})
	return http.StripPrefix(prefix, http.FileServer(http.FS(handler)))
	//return http.FileServer(http.FS(handler))
}